﻿using System;

namespace TileMaker
{
    partial class MainWindow
    {
        const float PI = (float)Math.PI;

        public static double Radians(double x)
        {
            return x * PI / 180.0F;
        }

        /// <summary>
        /// Returns the lateral distance between two coordinates
        /// </summary>
        /// <param name="lat1"></param>
        /// <param name="lon1"></param>
        /// <param name="lat2"></param>
        /// <param name="lon2"></param>
        /// <param name="Radius">Radius of the parent body in meters.</param>
        /// <returns></returns>
        public static double DistanceLat(double lat1, double lat2, double Radius)
        {
            double R = Radius / 1000.0f;
            double dLat = Radians(lat2 - lat1);
            lat1 = Radians(lat1);
            lat2 = Radians(lat2);

            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2);
            double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

            return R * c;
        }

        /// <summary>
        /// Returns the longitudinal distance between two coodrinates.
        /// </summary>
        /// <param name="lon1"></param>
        /// <param name="lon2"></param>
        /// <param name="lat"></param>
        /// <param name="Radius">in meters.</param>
        /// <returns></returns>
        public static double DistanceLon(double lon1, double lon2, double lat, double Radius)
        {
            double R = Radius / 1000.0f;
            double dLon = Radians(lon2 - lon1);

            double a = Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat) * Math.Cos(lat);
            double c = 2*Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a));

            return R * c;
        }

        /// <summary>
        /// Returns the length with the most appropriate unit.
        /// </summary>
        /// <param name="input">Input in meters.</param>
        /// <param name="Format">Format as after the colon in String.Format. Can be left empty.</param>
        /// <returns></returns>
        public static string WithCorrectUnit(double input, string Format)
        {
            if (!String.IsNullOrWhiteSpace(Format)) Format = ":" + Format;

            if (input > 850)
                return String.Format("{0" + Format + "} km", input / 1000);
            else if (input > .9)
                return String.Format("{0" + Format + "} m", input);
            else if (input > .009)
                return String.Format("{0" + Format + "} cm", input * 100);
            else
                return String.Format("{0" + Format + "} mm", input * 1000);
        }
    }
}
